﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PreeRegisterModel;
using System.Data;
using PreeRegisterDAL;
using DrSoftsFrame;
using Newtonsoft.Json.Linq;
using System.Web;

namespace PreeRegisterBLL
{
    public class WorkBLL
    {
        /// <summary>
        /// 获取排班号源信息
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static WorkUpdateResponseModel WorkUpdate(WorkUpdateRequestModel request)
        {
            try
            {
                DoctorUpdateResponseBodyModel doctorUpdateResponseBodyModel = DoctorUpdateBLL.GetDoctorUpdate(request.body.deptid);
                CommonBLL.WriteFile_New(CommonBLL.bizCode_workUpdate,
                string.Format("排班更新接口，科室ID：{0}\r\n，获取到的医生count：{1}", request.body.deptid, doctorUpdateResponseBodyModel.doctors.Count));
                WorkUpdateResponseModel workUpdateResponseModel = new WorkUpdateResponseModel();
                int synDate = 9;
                if (request.body.dates == DateTime.Now.ToString("yyyy-MM-dd"))
                {
                    synDate = 1;
                }
                workUpdateResponseModel = GetWorkUpdate(request, doctorUpdateResponseBodyModel, synDate);

                return workUpdateResponseModel;
            }
            catch (Exception err)
            {
                throw;
            }
        }


        /// <summary>
        /// 排班号源更新，遍历科室下的医生，并以科室为单位返回。
        /// </summary>
        /// <param name="request"></param>
        /// <param name="doctorId"></param>
        /// <param name="SynWorkDay"></param>
        /// <returns></returns>
        private static WorkUpdateResponseModel GetWorkUpdate(WorkUpdateRequestModel request, DoctorUpdateResponseBodyModel doctorUpdateResponseBodyModel, int SynWorkDay)
        {
            try
            {
                WorkUpdateResponseModel workUpdateResponseModel = new WorkUpdateResponseModel();

                WorkUpdateBodyModel workUpdateBodyModel = new WorkUpdateBodyModel();
                List<Work> works = new List<Work>();
                foreach (DoctorUpdateModel doctor in doctorUpdateResponseBodyModel.doctors)
                {
                    string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetOutPatientWorkSchedules?parameters=";
                    StringBuilder head = new StringBuilder();
                    StringBuilder body = new StringBuilder();
                    head.Append("{head:\"\"");
                    body.Append("{");
                    body.AppendFormat("\"DoctorCode\":\"{0}\",", doctor.id);
                    body.AppendFormat("\"Days\":\"{0}\"", SynWorkDay);
                    body.Append("}");
                    string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
                    postData += "\"}";
                    url += postData;
                    CommonBLL.WriteFile_New(CommonBLL.bizCode_workUpdate,
                        string.Format("排班更新接口，医生ID：{0}\r\n，请求URL：{1}", doctor.id, url));
                    // CommonBLL.WriteLog("排班更新接口请求URL:\r\n" + postData + "\r\n\r\n");
                    JObject obj = CommonBLL.HttpPost_CZHP(url);

                    workUpdateBodyModel.hospid = VariableBLL.HospitalId;
                    workUpdateBodyModel.atype = VariableBLL.atype;
                    string code = obj["code"].ToString();
                    if (string.Equals(code, "1"))
                    {
                        if (obj["result"] != null)
                        {
                            var mJObj = JArray.Parse(obj["result"].ToString());
                            foreach (var drv in mJObj)
                            {
                                if (string.Equals(drv["Date"].ToString(), request.body.dates))
                                {
                                    string deptid = request.body.deptid;
                                    string docDeptid = drv["Department"]["DepartmentCode"].ToString();
                                    if (string.Equals(deptid, docDeptid))
                                    {
                                        //获取排班信息
                                        Work work = new Work();
                                        work.docid = doctor.id;
                                        workUpdateBodyModel.deptid = drv["Department"]["DepartmentCode"].ToString();
                                        workUpdateBodyModel.deptname = drv["Department"]["Name"].ToString();
                                        work.docname = drv["Doctor"]["Name"].ToString();
                                        work.wid = drv["Code"].ToString();
                                        work.date = drv["Date"].ToString();
                                        work.mcount = drv["MaxRegisterCount"].ToString();
                                        work.tcount = drv["MaxRegisterCount"].ToString();
                                        work.acount = drv["MaxRegisterCount"].ToString();
                                        work.pcode = drv["TimeSection"]["Code"].ToString();
                                        work.stime = drv["TimeSection"]["StartTime"].ToString();
                                        work.etime = drv["TimeSection"]["EndTime"].ToString();
                                        work.rankid = drv["Rank"]["RankCode"].ToString();
                                        work.wrank = drv["Rank"]["RankName"].ToString();
                                        work.price = (double.Parse(drv["RegisterFee"].ToString()) * 100).ToString();
                                        work.ofee = (double.Parse(drv["VisitFee"].ToString()) * 100).ToString();// drv["VisitFee"].ToString();
                                        work.price2 = (double.Parse(drv["AddtionalFee"].ToString()) * 100).ToString(); //drv["AddtionalFee"].ToString();
                                        work.addr = drv["VisitRoom"].ToString();
                                        work.endtreat = drv["EndTreat"].ToString() == "False" ? "0" : "1";
                                        work.hoscode = "0";// drv["HOSCODE"].ToString();
                                        work.wtype = "1"; //drv["WTYPE"].ToString();

                                        // 如果是分时预约 则获取号源信息
                                        if (VariableBLL.atype.Equals("1"))
                                        {
                                            var mJObj_no = JArray.Parse(drv["WorkDetails"].ToString());
                                            List<WorkUpdateDetail> workDetails = new List<WorkUpdateDetail>();

                                            int icount = 0;
                                            foreach (var drvDetail in mJObj_no)
                                            {
                                                WorkUpdateDetail workDetail = new WorkUpdateDetail();

                                                workDetail.id = drvDetail["Code"].ToString();
                                                workDetail.inum = drvDetail["AppointmentOrder"].ToString();
                                                if (workDetail.inum.Length == 1)
                                                    workDetail.inum = "0" + workDetail.inum;
                                                workDetail.state = CommonBLL.ConvertState(drvDetail["AppointmentState"].ToString());
                                                // workDetail.time = drvDetail["TimeSection"]["StartTime"].ToString() + string.Format("({0})", workDetail.inum);
                                                //edit by zhuyr 20200718
                                                workDetail.time = drvDetail["TimeSection"]["StartTime"].ToString();
                                                workDetail.time = drvDetail["TimeSection"]["StartTime"].ToString() + "~" + drvDetail["TimeSection"]["EndTime"].ToString();

                                                //郭先菊 特殊处理
                                                if (CommonBLL.IsAddInResourceList(work.docid, work.date, drvDetail["TimeSection"]["StartTime"].ToString()))
                                                {
                                                    if (workDetail.state == "0")
                                                        icount++;
                                                    workDetails.Add(workDetail);
                                                }
                                            }
                                            work.no = workDetails;
                                            //count = icount;
                                        }
                                        //王治平 特殊处理
                                        if (CommonBLL.IsAddInWorkList(work.docid, work.date))
                                            works.Add(work);
                                    }
                                }
                            }
                            workUpdateBodyModel.hospid = VariableBLL.HospitalId;
                            workUpdateBodyModel.atype = CommonBLL.GetConfig("atype");
                            workUpdateBodyModel.works = works;
                        }
                    }

                }
                workUpdateResponseModel.head = VariableBLL.GetHead();
                workUpdateResponseModel.body = workUpdateBodyModel;

                return workUpdateResponseModel;
            }
            catch (Exception err)
            {

                throw;
            }
        }


        /// <summary>
        /// 获取排班&号源信息
        /// </summary>
        /// <param name="deptId"></param>
        /// <param name="doctorId"></param>
        /// <param name="workId"></param>
        /// <param name="SynWorkDay"></param>
        /// <returns></returns>
        public static WorkUpdateResponseModel GetWorkInfo(string doctorId, string workId, int SynWorkDay, out int count)
        {
            try
            {
                count = 99;
                WorkUpdateResponseModel workUpdateResponseModel = new WorkUpdateResponseModel();

                WorkUpdateBodyModel workInfoRequestModel = new WorkUpdateBodyModel();

                string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetOutPatientWorkSchedules?parameters=";
                StringBuilder head = new StringBuilder();
                StringBuilder body = new StringBuilder();
                head.Append("{head:\"\"");
                body.Append("{");
                body.AppendFormat("\"DoctorCode\":\"{0}\",", doctorId);
                body.AppendFormat("\"Days\":\"{0}\"", SynWorkDay);
                body.Append("}");
                string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
                postData += "\"}";
                url += postData;
                JObject obj = CommonBLL.HttpPost_CZHP(url);

                workInfoRequestModel.hospid = VariableBLL.HospitalId;
                workInfoRequestModel.atype = VariableBLL.atype;
                string code = obj["code"].ToString();
                if (string.Equals(code, "1"))
                {
                    if (obj["result"] != null)
                    {
                        var mJObj = JArray.Parse(obj["result"].ToString());
                        List<Work> works = new List<Work>();
                        foreach (var drv in mJObj)
                        {
                            if (string.Equals(workId, drv["Code"].ToString()))
                            {
                                //获取排班信息
                                Work work = new Work();
                                work.docid = doctorId;
                                workInfoRequestModel.deptid = drv["Department"]["DepartmentCode"].ToString();
                                workInfoRequestModel.deptname = drv["Department"]["Name"].ToString();
                                work.docname = drv["Doctor"]["Name"].ToString();
                                work.wid = drv["Code"].ToString();
                                work.date = drv["Date"].ToString();
                                work.mcount = drv["MaxRegisterCount"].ToString();
                                work.tcount = drv["MaxRegisterCount"].ToString();
                                work.acount = drv["MaxRegisterCount"].ToString();
                                work.pcode = drv["TimeSection"]["Code"].ToString();
                                work.stime = drv["TimeSection"]["StartTime"].ToString();
                                work.etime = drv["TimeSection"]["EndTime"].ToString();
                                work.rankid = drv["Rank"]["RankCode"].ToString();
                                work.wrank = drv["Rank"]["RankName"].ToString();
                                work.price = (double.Parse(drv["RegisterFee"].ToString()) * 100).ToString();
                                work.ofee = (double.Parse(drv["VisitFee"].ToString()) * 100).ToString();// drv["VisitFee"].ToString();
                                work.price2 = (double.Parse(drv["AddtionalFee"].ToString()) * 100).ToString(); //drv["AddtionalFee"].ToString();
                                work.addr = drv["VisitRoom"].ToString();
                                work.endtreat = drv["EndTreat"].ToString() == "False" ? "0" : "1";
                                work.hoscode = "0";// drv["HOSCODE"].ToString();
                                work.wtype = "1"; //drv["WTYPE"].ToString();

                                // 如果是分时预约 则获取号源信息
                                if (VariableBLL.atype.Equals("1"))
                                {
                                    var mJObj_no = JArray.Parse(drv["WorkDetails"].ToString());
                                    List<WorkUpdateDetail> workDetails = new List<WorkUpdateDetail>();

                                    int icount = 0;
                                    foreach (var drvDetail in mJObj_no)
                                    {
                                        WorkUpdateDetail workDetail = new WorkUpdateDetail();

                                        workDetail.id = drvDetail["Code"].ToString();
                                        workDetail.inum = drvDetail["AppointmentOrder"].ToString();
                                        if (workDetail.inum.Length == 1)
                                            workDetail.inum = "0" + workDetail.inum;
                                        // workDetail.time = drvDetail["TimeSection"]["StartTime"].ToString() + string.Format("({0})", workDetail.inum);
                                        //edit by zhuyr 20200718
                                        workDetail.time = drvDetail["TimeSection"]["StartTime"].ToString();
                                        workDetail.time = drvDetail["TimeSection"]["StartTime"].ToString() + "~" + drvDetail["TimeSection"]["EndTime"].ToString();

                                        //郭先菊 特殊处理
                                        if (CommonBLL.IsAddInResourceList(work.docid, work.wid, drvDetail["TimeSection"]["StartTime"].ToString()))
                                        {
                                            if (workDetail.state == "0")
                                                icount++;
                                            workDetails.Add(workDetail);
                                        }
                                    }

                                    work.no = workDetails;
                                    count = icount;
                                }
                                //王治平 特殊处理
                                if (CommonBLL.IsAddInWorkList(work.docid, work.date))
                                {
                                    works.Add(work);
                                }
                            }
                        }
                        workInfoRequestModel.works = works;
                        workUpdateResponseModel.head = VariableBLL.GetHead();
                        workUpdateResponseModel.body = workInfoRequestModel;

                        return workUpdateResponseModel;
                    }
                }
                return workUpdateResponseModel;
            }
            catch (Exception ex)
            {

                throw;
            }
        }

        /// <summary>
        /// 校验输入参数
        /// </summary>
        /// <param name="request"></param>
        /// <param name="ErrMsg"></param>
        /// <returns></returns>
        private static bool VerifyInput(WorkUpdateRequestModel request, ref string ErrMsg)
        {
            try
            {
                if (request.body.optype.Trim() == "")
                {
                    ErrMsg = "查询方式不能为空！";
                    return false;
                }
                if (request.body.optype.Trim() == "1")
                {
                    if (request.body.deptid.Trim() == "")
                    {
                        ErrMsg = "科室ID不能为空！";
                        return false;
                    }

                    if (request.body.docid.Trim() == "")
                    {
                        ErrMsg = "医生ID不能为空！";
                        return false;
                    }
                }
                if (request.body.optype.Trim() == "2")
                {
                    if (request.body.ids.Trim() == "")
                    {
                        ErrMsg = "排班ID不能为空！";
                        return false;
                    }
                }
                return true;
            }
            catch (Exception err)
            {

                throw;
            }
        }

        /// <summary>
        /// 反序列化请求字符串
        /// </summary>
        /// <param name="head_json"></param>
        /// <param name="body_json"></param>
        /// <returns></returns>
        public static WorkUpdateRequestModel ReturnWorkUpdateRequestModel(string head_json, string body_json)
        {
            try
            {
                Head head = csSerialize.RequestHeadInfo(head_json);

                WorkUpdateModel body = csSerialize.WorkUpdateRequestBodyInfo(body_json);

                WorkUpdateRequestModel workUpdateRequestModel = new WorkUpdateRequestModel();
                workUpdateRequestModel.head = head;
                workUpdateRequestModel.body = body;
                return workUpdateRequestModel;
            }
            catch (Exception err)
            {

                throw;
            }
        }


        /// <summary>
        /// 获取HIS排班原始报文
        /// </summary>
        /// <param name="deptId"></param>
        /// <param name="doctorId"></param>
        /// <param name="workId"></param>
        /// <param name="SynWorkDay"></param>
        /// <returns></returns>
        public static string GetWorkJson(string doctorId, string workId, int SynWorkDay)
        {
            try
            {
                string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetOutPatientWorkSchedules?parameters=";
                StringBuilder head = new StringBuilder();
                StringBuilder body = new StringBuilder();
                head.Append("{head:\"\"");
                body.Append("{");
                body.AppendFormat("\"DoctorCode\":\"{0}\",", doctorId);
                body.AppendFormat("\"Days\":\"{0}\"", SynWorkDay);
                body.Append("}");
                string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
                postData += "\"}";
                url += postData;
                CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "1：获取医生排班请求明文：\r\n" + CommonBLL.ConvertJsonString(body.ToString()));
                CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "1：获取医生排班请求地址：\r\n" + url);
                string jsonData = CommonBLL.HttpPost_JSON(url, "");
                CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "1：获取医生排班返回密文：\r\n" + jsonData);
                return jsonData;
            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}
